from . import auth_bp
from flask import request, jsonify
from .models import User, Role, Permission, Menu
from app import db, csrf, cache
from flask.views import MethodView, View


class GenericView(View):
    def __init__(self):
        super(GenericView, self).__init__()

    def dispatch_request(self):
        return jsonify({'code': 0, 'info': ''})


class RoleView(MethodView):
    def get(self):
        # queryset = Role.query.all()
        # item_list = [item.to_dict() for item in queryset]
        return jsonify({'code': 0, 'item_list': ""})

    def post(self):
        pass


# 建议路由代码放在app/__init__中
auth_bp.add_url_rule(
    '/method/get',
    view_func=RoleView.as_view('role')
)

auth_bp.add_url_rule(
    '/generic/get', view_func=GenericView.as_view('generic')
)


@auth_bp.route("/role/list", methods=['GET'])
# @cache.cached(timeout=600, key_prefix="role_list")
def role_list():
    """
    列出角色列表
    :return:
    """
    queryset = Role.query.all()
    item_list = [item.to_dict() for item in queryset]
    return jsonify({'code': 0, 'item_list': item_list})


@auth_bp.route('/role/add', methods=['POST'])
def role_add():
    """
    添加角色属性
    :return:
    """
    params = request.get_json()
    role_name = params.get('role_name')
    if Role.query.filter_by(role_name=role_name).first():
        return jsonify({'code': -1, 'info': '角色已存在'})
    role = Role(role_name=role_name)
    db.session.add(role)
    db.session.commit()
    return jsonify({'code': 0, 'info': 'ok'})


@auth_bp.route('/role/del', methods=['POST'])
def role_del():
    params = request.get_json()
    ids = params.get('ids')
    # Role.query.filter(Role.id.in_(ids)).delete(synchronize_session=False)
    roles = Role.query.filter(Role.id.in_(ids))
    db.session.delete(roles)
    db.session.commit()
    return jsonify({'code': 0, 'info': 'ok'})


@auth_bp.route('/role/modify')
def role_modify():
    pass


@auth_bp.route('/perm/list', methods=['GET'])
def perm_list():
    queryset = Permission.query.all()
    item_list = [item.to_dict() for item in queryset]
    return jsonify({'code': 0, 'result': item_list, 'info': 'ok', 'error': ''})


@auth_bp.route('/perm/add', methods=['POST'])
@csrf.exempt
def perm_add():
    params = request.get_json()
    title = params.get('title')
    if not title:
        return jsonify({'code': -1, 'info': 'error', 'result': [], 'error': '没有权限名称'})
    if Permission.query.filter_by(title=title).first():
        return jsonify({'code': -1, 'info': 'error', 'result': [], 'error': '权限已存在'})
    try:
        perm = Permission(**params)    # id, title, url, parent_id, permission_desc, is_menu, menu
        db.session.add(perm)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 5000, 'info': 'error', 'result': [], 'error': '添加权限失败'})
    return jsonify({'code': 0, 'info': 'ok', 'result': [], 'error': ''})


@auth_bp.route('/perm/del', methods=['POST'])
def perm_del():
    params = request.get_json()
    ids = params.get('ids')
    Permission.query.filter(Permission.id.in_(ids)).delete(synchronize_session=False)
    db.session.delete()
    db.session.commit()
    return jsonify({'code': 0, 'info': 'ok', 'result': [], 'error': ''})


@auth_bp.route('/perm/modify', methods=['POST'])
def perm_modify():
    params = request.get_json()
    if params.get('id'):
        id_ = params.pop('id')
    else:
        return jsonify({'code': -1, 'info': 'error', 'result': [], 'error': '没有传参权限id'})
    try:
        Permission.query.filter_by(id=id_).update(params)
        db.session.add()
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 5000, 'info': 'error', 'result': [], 'error': '权限修改失败'})

    return jsonify({'code': 0, 'info': 'ok', 'result': [], 'error': ''})
